import { useDeviceListStore, useDeviceShare, useHomeStore } from '@/hooks';
import useBoolean from '@/hooks/useBoolean';
import useEvent from '@/hooks/useEvent';
import { cancelDeviceShare, removeReceiveShareDevices } from '@/services/share';
import { isSameDevice } from '@/utils';
import { GStyleSheet } from '@/utils/DarkMode';
import { Button, Collapse } from '@taroify/core';
import { Image, ScrollView, View } from '@tarojs/components';
import Taro from '@tarojs/taro';
import { observer } from 'mobx-react';
import React, { useEffect, useLayoutEffect, useRef, useState } from 'react';
import manageIcon from '../images/manage.png';
import Device from './device';


const dstyles = GStyleSheet.create({
  rooms: {
    flex: 1,
    overflow: 'hidden'
  },
  scrollView: {
    height: '100%',
  },
  item: {
    marginTop: '28rpx',
  },
  bottom: {
    height: 80,
    display: 'flex',
    alignItems: 'center',
    justifyContent: 'center',
  },
  manageIcon: {
    width: 16,
    height: 16,
    marginRight: 10,
  },
  button: {
    width: 130,
    margin: '0 24rpx',
  },
  line: {
    height: 1,
    background: '#F0F0F0',
  }
});

function useLazyRender(active: boolean) {
  const [canRender, setCanRender] = useState(active);
  const canRenderRef = useRef(canRender);

  useLayoutEffect(() => {
    if (active && !canRenderRef.current) {
      canRenderRef.current = true;
      setCanRender(true);
    }
  }, [active]);
  return canRender;
}

interface Props {
  isOwner: boolean;
  active: boolean;
}

const Rooms: React.FC<Props> = ({
  isOwner,
  active,
}) => {
  const canRender = useLazyRender(active);
  const deviceShare = useDeviceShare()
  const homes = useHomeStore();
  const rooms = isOwner ? deviceShare.list : deviceShare.receiveList;
  const devices = useDeviceListStore();
  const [selectedRoomId, setSelectedRoomId] = useState(rooms[0] ? rooms[0].roomId ?? 0 : 0);
  const [selectedDevices, setSelectedDevices] = useState<IDevice[]>([]);

  const [isManageMode, { setFalse: exitManageMode, setTrue: enterManageMode }] = useBoolean();

  useEffect(() => {
    if (active) {
      isOwner ? deviceShare.fetchList() : deviceShare.fetchReceiveList();
    }
  }, [active]);

  useEffect(() => {
    if (!isManageMode) {
      setSelectedDevices([]);
    }
  }, [isManageMode]);

  useEffect(() => {
    if (!rooms[0]) {
      return;
    }
    setSelectedRoomId((oldId) => {
      if (!oldId) {
        return rooms[0].roomId;
      }
      return oldId;
    });
  }, [rooms]);

  const handlePress = useEvent((device: IDevice) => {
    if (isManageMode) {
      const index = selectedDevices.findIndex(d => isSameDevice(d, device));
      index < 0
        ? setSelectedDevices([...selectedDevices, device])
        : setSelectedDevices([...selectedDevices.slice(0, index), ...selectedDevices.slice(index + 1)])
      return;
    }
    Taro.navigateTo({
      url: `/pages/share/users/index?pk=${device.productKey}&mac=${device.mac}`,
    })
  });

  const stopShare = useEvent(() => {
    if (selectedDevices.length === 0) {
      return;
    }
    cancelDeviceShare(selectedDevices).then((res) => {
      if (res.success) {
        deviceShare.fetchList();
        // exitManageMode();
      }
    })
  });

  const exitShare = useEvent(() => {
    if (selectedDevices.length === 0) {
      return;
    }
    removeReceiveShareDevices(selectedDevices).then((res) => {
      if (res.success) {
        deviceShare.fetchReceiveList();
        exitManageMode();
      }
    })
  });

  const styles = dstyles.useDynamicStyle();

  const hasDevices = rooms.some(r => r.shareDeviceList?.length > 0);

  if (!homes.curHome) {
    return null;
  }

  return canRender ? (
    <>
      <View style={styles.rooms}>
        <ScrollView style={styles.scrollView} scrollY>
          <Collapse accordion value={selectedRoomId} onChange={setSelectedRoomId}>
            {rooms.map((r) => {
              const index = homes.curHome?.rooms.findIndex(hr => hr.id === r.roomId) ?? -1;
              const homeRoom = index > -1 ? homes.curHome?.rooms[index] : null;
              return homeRoom && (
                <>
                  <Collapse.Item
                    key={r.roomId}
                    value={r.roomId}
                    title={homeRoom.default ? '默认分组' : r.roomName || `分组${index}`}
                    style={styles.item}
                  >
                    {
                      r.shareDeviceList.map((d, i) => {
                        const data = devices.data.find(item => isSameDevice(d, item));
                        const selected = isManageMode && !!selectedDevices.find(item => isSameDevice(d, item));
                        return data && (
                          <>
                            <Device
                              key={data.deviceId}
                              data={data}
                              numberOfUsers={isOwner ? d.shareNumber : null}
                              isSelectMode={isManageMode}
                              selected={selected}
                              onPress={handlePress}
                            />
                            {
                              i !== r.shareDeviceList.length - 1 && (
                                <View style={styles.line} />
                              )
                            }
                          </>
                        )
                      })
                    }
                  </Collapse.Item>
                </>
              )
            })}
          </Collapse>
        </ScrollView>
      </View>
      <View style={styles.bottom}>
        {
          isManageMode
            ? (
              <>
                <Button
                  variant='outlined'
                  color='primary'
                  onClick={exitManageMode}
                  style={styles.button}
                >
                  完成
                </Button>
                <Button
                  variant='contained'
                  color={isOwner ? 'primary' : 'danger'}
                  style={styles.button}
                  disabled={selectedDevices.length === 0}
                  onClick={isOwner ? stopShare : exitShare}
                >
                  {isOwner ? '停止分享' : '删除'}
                </Button>
              </>
            ) : (
              <Button
                variant='contained'
                shape='round'
                color='primary'
                icon={<Image src={manageIcon} style={styles.manageIcon} />}
                disabled={!hasDevices}
                onClick={enterManageMode}
              >
                管理
              </Button>
            )
        }
      </View>
    </>
  ) : null;
};

export default observer(Rooms);
